import React, { useEffect, useState } from 'react';
import { Button, Form, Input, message, Modal, Select, Space, Spin } from 'antd';
import { DeleteOutlined, PlusCircleOutlined } from '@ant-design/icons';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import styles from './index.less';
import { judgmentFieldValue, monthHeadList, monthHeadListSave } from '../../service';
// @ts-ignore
import { TRAlert, TRMessage } from '#/components';

interface IProps {
  queryValue: any;
  fetchData: () => void;
  onPress: (data: Record<string, any>) => void;
  onOk: () => void;
  marketList: any[];
}

const ApplyModalComponent = (props: IProps) => {
  const { onOk, onPress, queryValue, marketList } = props;

  const [form] = Form.useForm();
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const [marketId, setMarketId] = useState(queryValue.marketId);

  const fetchList = async (marketId: string) => {
    setLoading(true);
    const res = await monthHeadList(marketId);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      form.setFieldsValue({
        fields: res?.data || [],
      });
    } else {
      message.error(res?.message || '查询字段失败!');
    }
    setLoading(false);
  };

  useEffect(() => {
    (async () => {
      await fetchList(queryValue.marketId);
    })();
  }, []);

  /**
   * 取消按钮
   */
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  // 保存字段
  const onSaveData = async (v: any) => {
    const res = await monthHeadListSave(v);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      await fetchList(marketId);
      onOk();
      _onCancel();
      message.success('保存字段成功!');
    } else {
      message.error(res?.message || '保存字段失败!');
    }
  };

  const _onOk = async () => {
    form &&
      form.validateFields().then(async (value) => {
        const { fields = [] } = value;
        const data = fields?.map((i: any, index: number) => ({
          ...i,
          marketId: marketId,
          // fieldSort: index,
        }));
        setLoading(true);
        const res: any = await onSaveData(data);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setVisible(false);
          onPress({ index: 1, statusCode: HttpCode.SUCCESS });
        }
        setLoading(false);
      });
  };

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={loading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={loading}>
        确定
      </Button>,
    ];
  };

  const changeMarketId = async (v: string) => {
    setMarketId(v);
    await fetchList(v);
  };

  return (
    <Modal
      width={650}
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} alt={''} />
          <span className={styles.title}>字段管理</span>
          <Select
            style={{ width: 200, marginLeft: 16 }}
            value={marketId}
            options={marketList}
            onChange={changeMarketId}
          />
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        <Spin spinning={loading}>
          <Form
            className={styles.form}
            form={form}
            name="apply"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 14 }}
            labelAlign="left"
            colon={false}
            autoComplete="off"
            requiredMark={false}
          >
            {/* will 动态字段配置 */}
            <Form.List name="fields">
              {(fields, { add, remove }) => (
                <>
                  {fields.map(({ key, name, fieldKey, ...restField }) => (
                    <Space
                      key={key}
                      align="baseline"
                      style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}
                    >
                      <Form.Item
                        {...restField}
                        label={<span style={{ color: '#7A7D7F' }}>字段标题</span>}
                        name={[name, 'fieldTitle']}
                        fieldKey={[fieldKey, 'fieldTitle']}
                        rules={[{ required: true, message: '请输入字段标题' }]}
                      >
                        <Input placeholder="字段标题" allowClear />
                      </Form.Item>

                      <Form.Item
                        {...restField}
                        label={<span style={{ color: '#7A7D7F' }}>字段单位</span>}
                        name={[name, 'fieldUnits']}
                        fieldKey={[fieldKey, 'fieldUnits']}
                        rules={[{ required: true, message: '请输入字段单位' }]}
                      >
                        <Input placeholder="字段单位" allowClear />
                      </Form.Item>

                      <DeleteOutlined
                        style={{ color: '#FF5757' }}
                        onClick={async () => {
                          const fieldsList = form.getFieldsValue()?.fields || [];
                          const value = fieldsList?.[name] || {};
                          if (value?.id) {
                            const res = await judgmentFieldValue(value.id);
                            if (res && res.statusCode === HttpCode.SUCCESS) {
                              const obj = await TRAlert.eamDelete('是否确认删除字段？');
                              if (obj?.index === 1) {
                                remove(name);
                              }
                            } else {
                              const obj = await TRAlert.eamDelete(
                                res?.message || '当前字段还有数据，是否确认仍要删除该字段？',
                              );
                              if (obj?.index === 1) {
                                remove(name);
                              }
                            }
                          } else {
                            remove(name);
                          }
                        }}
                      />
                    </Space>
                  ))}

                  <Form.Item wrapperCol={{ span: 11 }}>
                    <Button
                      type="link"
                      onClick={() => {
                        if (fields.length >= 10) {
                          return TRMessage.warning('当前字段个数已达十个！');
                        } else {
                          add();
                        }
                      }}
                      block
                      icon={<PlusCircleOutlined />}
                    >
                      添加字段
                    </Button>
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Form>
        </Spin>
      </div>
    </Modal>
  );
};

class ApplyModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ApplyModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

// @ts-ignore
export default new ApplyModal();
